<template>
  <div class="g-page-container">
    <PageHeader title="潜客创建" />
    <div class="g-content-container">
      <CustomerSearchForm ref="search-form" @search="searchLoadTableList" />

      <ButtonGroup :options="middleButtons" @click="handleButtonClick" />
      <MainTableList
        :loading="loading"
        :data-source="dataSource"
        :columns="columns"
        slot-name="serialNumber"
        :row-selection="rowSelectionMixin"
        :pagination="paginationMixin"
        @change="handleTableChange"
        @number-click="handleNumberClick"
      />
    </div>
    <component
      :is="currentComponent"
      :has-default="hasDefault"
      :visible.sync="visibleDrawer"
      :current-node="currentNode"
      :price-id="priceId"
      :process-id="processId"
      :curr-status="currStatus"
      @fresh="loadTableList"
      @change-currstatus="changeCurrstatus"
    />
    <DialogCustomerTransferAdmin
      :visible.sync="visibleModal"
      :selecteds="selectedInfos"
      number="客户编号"
      @fresh="loadTableList"
    />
  </div>
</template>

<script>
import CustomerSearchForm from './components/customerSearchForm.vue';
import mixinTable from '@/mixins/mixin-table.js';
import mixinPublic from './components/mixin';

import MainTableList from './components/mainTableList.vue';

import DialogCustomerTransferAdmin from '@/components/dialog/DialogCustomerTransferAdmin.vue';
import DrawerAddCustomer from './components/DrawerAddCustomer.vue';
import DrawerEditCustomer from './components/DrawerEditCustomer.vue';
import DrawerDeparmentAudit from './components/DrawerDeparmentAudit.vue';
import DrawerKapmChiefAudit from './components/DrawerKapmChiefAudit.vue';
import DrawerSaleChiefAudit from './components/DrawerSaleChiefAudit.vue';
import DrawerEnd from './components/DrawerEnd.vue';

import {
  customerListByPage,
  postCustomerDelete,
  getQueryDetail,
} from '@/api/customerApi.js';
import monent from 'moment';
import { CUSTOMER_NODE } from '@/constants/index';

export default {
  components: {
    CustomerSearchForm,
    MainTableList,
    DialogCustomerTransferAdmin,
    DrawerAddCustomer,
    DrawerEditCustomer,
    DrawerDeparmentAudit,
    DrawerKapmChiefAudit,
    DrawerSaleChiefAudit,
    DrawerEnd,
  },
  mixins: [mixinTable, mixinPublic],
  data() {
    return {
      currentComponent: '',
      asc: true,
      loading: false,
      dataSource: [],
      visibleModal: false,
      filedsKeys: [],
      currentNode: CUSTOMER_NODE[1],
      columnKey: '',
      visibleDrawer: false,
      selectedInfos: [],
      data: [],
      priceId: undefined,
      form: {},
      logs: [],
      processId: undefined,
      currStatus: '1',
      formInfo: {},
      hasDefault: false,
    };
  },
  computed: {
    middleButtons() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'add',
          label: '新增潜客',
          type: 'primary',
          icon: 'plus',
          authKey: 'customer-button-add',
        },
        {
          key: 'delete',
          label: '删除',
          type: '',
          icon: 'delete',
          authKey: 'customer-button-delete',
          disabled,
        },
        {
          key: 'retweet',
          label: '转他人处理',
          type: '',
          icon: 'retweet',
          authKey: 'customer-button-transfer',
          disabled,
        },
      ];
    },

    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          dataIndex: 'dataIndex',
          width: 30,
          required: true,
          customRender: (t, r, index) => {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '客户编号',
          dataIndex: 'code',
          key: 'code',
          width: 120,
          sorter: true,
          required: true,
          scopedSlots: { customRender: 'serialNumber' },
        },
        {
          align: 'center',
          title: '客户名称',
          dataIndex: 'customerName',
          key: 'customerName',
          width: 120,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'name',
          key: 'name',
          width: 60,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '客户分类',
          dataIndex: 'classificationCode',
          key: 'classificationCode',
          width: 80,
          sorter: true,
          ellipsis: true,
          customRender: text => this.escapeCustomerType[text],
        },
        {
          align: 'center',
          title: '当前状态',
          dataIndex: 'currStatus',
          key: 'currStatus',
          width: 60,
          sorter: true,
          ellipsis: true,
          customRender: text => this.escapeState[text],
        },
        {
          align: 'center',
          title: '当前节点',
          dataIndex: 'nodeCode',
          key: 'nodeCode',
          width: 80,
          sorter: true,
          ellipsis: true,
          customRender: text => this.escapeCustomerNode[text],
        },
        {
          align: 'center',
          title: '当前处理人',
          dataIndex: 'handleUserName',
          key: 'handleUserName',
          width: 80,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '销售组织',
          dataIndex: 'salesOrgCode',
          key: 'salesOrgCode',
          width: 60,
          sorter: true,
          ellipsis: true,
          customRender: text => this.escapeSalesOrgCode[text],
        },
        {
          align: 'center',
          title: '销售组',
          dataIndex: 'salesGroupCode',
          key: 'salesGroupCode',
          width: 100,
          sorter: true,
          ellipsis: true,
          customRender: (value, row, index) => {
            value = value.split(',');
            let data = this.getltcoledList || {};
            let info = value?.map(item => {
              return data[item];
            });
            return info.join('，');
          },
        },
        {
          align: 'center',
          title: 'KAPM组',
          width: 100,
          dataIndex: 'pmGroupCode',
          key: 'pmGroupCode',
          sorter: true,
          ellipsis: true,
          customRender: (value, row, index) => {
            value = value.split(',');
            let data = this.getltcoledList || {};
            let info = value?.map(item => {
              return data[item];
            });
            return info.join('，');
          },
        },
        {
          align: 'center',
          title: '创建人',
          width: 60,
          dataIndex: 'createUserName',
          key: 'createUserName',
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '创建时间',
          width: 100,
          dataIndex: 'createTime',
          key: 'createTime',
          sorter: true,
          ellipsis: true,
        },
      ];
      // console.log(columns);
      return columns;
    },
    escapeState() {
      return this.$store.state.dictionary.dict['state'] || {};
    },
    escapeCustomerNode() {
      return this.$store.state.dictionary.dict['customer_node'] || {};
    },
    escapeSalesOrgCode() {
      return this.$store.getters.getOrg({
        code: 'ltcsmsizebu',
        isDict: true,
      }) || {};
    },
    escapeCustomerType() {
      return this.$store.state.dictionary.dict['customer_type'] || {};
    },
    getltcoledList() {
      const list1 = this.$store.getters.getOrg({
        code: 'ltcorgoled',
        type: 'sales',
        isDict: true,
      });
      const list2 = this.$store.getters.getOrg({
        code: 'ltcorgltps',
        type: 'sales',
        isDict: true,
      });
      const list3 = this.$store.getters.getOrg({
        code: 'ltcorgoled',
        type: 'kapm',
        isDict: true,
      });
      const list4 = this.$store.getters.getOrg({
        code: 'ltcorgltps',
        type: 'kapm',
        isDict: true,
      });
      // console.log({ ...list1, ...list2, ...list3, ...list4 })
      return { ...list1, ...list2, ...list3, ...list4 };
    },
  },
  created() {
    // this.loadTableList();
    // this.$nextTick(() => {
    // this.currentComponent = 'DrawerEditCustomer';
    // this.visibleDrawer = true;
    this.getCustomerListByPage();
    // });
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.query?.id) {
        vm.handleNumberClick(to.query);
      } else if (to.query?.type === 'addCustomer') {
        vm.addCallback();
      }
    });
  },
  methods: {
    handleSelectFileds(filedsKeys) {
      this.filedsKeys = filedsKeys;
    },
    async getCustomerListByPage() {
      let data = this.$refs['search-form']?.getSearchParams;
      this.loading = true;
      try {
        const res = await customerListByPage({
          ...data,
        });
        let dataList = res?.data?.data?.records;
        this.dataSource = dataList || [];
        this.paginationMixin.total = res?.data?.data?.total;
        this.loading = false;
      } catch (err) {
        console.log(err, 'err');
        this.loading = false;
      }
    },
    async handleNumberClick(record) {
      let currentNode = CUSTOMER_NODE[Number(record.nodeCode)];
      if (!currentNode) {
        this.$message.error('非有效节点，无法进入！');
        return;
      }
      if (record.nodeCode === '1') {
        const res = await getQueryDetail({ customerId: record.id });
        const isCurrentProcessor = res?.data?.data?.isCurrentProcessor;
        if (isCurrentProcessor) {
          this.currentNode = CUSTOMER_NODE[Number(record.nodeCode)];
        } else {
          this.currentNode = CUSTOMER_NODE[Number(5)];
        }
      } else if (record.nodeCode === '6') {
        this.currentNode = CUSTOMER_NODE[Number(record.nodeCode)];
      } else {
        this.currentNode = CUSTOMER_NODE[Number(record.nodeCode)];
      }
      this.currStatus = record.currStatus;
      this.currentComponent = `Drawer${this.currentNode.key}`;
      this.processId = record.processId;
      this.priceId = record.id;
      this.visibleDrawer = true;
      // console.log(this.currentComponent);
    },
    searchLoadTableList() {
      this.paginationMixin.current = 1;
      this.loadTableList();
    },
    getSearchForm() {
      const form = this.$refs['search-form']?.getSearchParams || {};
      let { startCreateTime, endCreateTime } = form;
      form.startCreateTime = startCreateTime
        ? `${monent(startCreateTime).format('YYYY-MM-DD')} 00:00:00`
        : '';
      form.endCreateTime = endCreateTime
        ? `${monent(endCreateTime).format('YYYY-MM-DD')} 23:59:59`
        : '';
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      return { ...form, ...page };
    },
    async loadTableList() {
      let formData = this.getSearchForm();
      // 校验时间是否只输入一个
      if (!formData.startCreateTime && formData.endCreateTime) {
        this.$message.error('请选择开始时间');
        return;
      }
      if (formData.startCreateTime && !formData.endCreateTime) {
        this.$message.error('请选择结束时间');
        return;
      }
      this.loading = true;
      const result = await customerListByPage(formData).finally(
        () => (this.loading = false)
      );
      this.paginationMixin.total = result?.data?.data?.total || 0;
      this.dataSource = result?.data?.data?.records || [];
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      // console.log(page,sorter);
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.loadTableList();
    },
    handleButtonClick(key) {
      // console.log(key);
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    addCallback() {
      this.currentComponent = 'DrawerAddCustomer';
      this.visibleDrawer = true;
    },
    async retweetCallback() {
      const selectedInfos = this.rowSelectionMixin.selectedRows
        .filter(item => item.currStatus === '2')
        .map((item, i) => {
          return {
            serialNumber: item.code,
            currentUserId: item.handleUserId,
            planId: item.id,
            handleUserName: item.handleUserName,
            name: [],
          };
        });
      if (!selectedInfos.length) {
        this.$message.info(
          `仅可转审批中的数据，现有 ${selectedInfos.length} 条！`
        );
        return;
      }
      try {
        await this.$confirm(
          `仅可转审批中的数据，共 ${selectedInfos.length} 条，是否确认？`
        );

        this.visibleModal = true;
        this.selectedInfos = selectedInfos;
      } catch (error) {
        // console.log('error: ', error);
      }
    },

    async deleteCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys || [];
      if (!ids.length) {
        this.$message.info('请先选择数据！');
        return;
      }
      try {
        await this.$confirm(`该操作将删除 ${ids.length} 条数据，是否确认？`);
        const checkedRows = this.dataSource.reduce((pre, cur) => {
          if (ids.includes(cur.id)) {
            pre.push(cur);
          }
          return pre;
        }, []);
        const isValid = checkedRows.some(item => item.currStatus !== '1');
        if (isValid) {
          this.$message.error('只可删除草稿状态的潜客！');
          return;
        }

        await postCustomerDelete(this.rowSelectionMixin.selectedRowKeys);
        this.$message.success('删除成功');
        this.rowSelectionMixin.selectedRowKeys = [];
        this.loadTableList();
      } catch (error) {
        // console.log('error: ', error);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.table-container {
  padding: 15px 20px;
  height: calc(100vh - 160px);
  box-sizing: border-box;
}
</style>
